package com.getword.service.impl;

import com.getword.domain.Comments;
import com.getword.domain.Reply;
import com.getword.mongodao.CommentsRepository;
import com.getword.service.CommentsService;
import com.getword.web.model.Result;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
//@Transactional(readOnly = false)
public class CommentsServiceImpl implements CommentsService {
    @Autowired
    private CommentsRepository commentsRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Result getCommentsByArticleId(String articleId) {
        List<Comments> comments = commentsRepository.findCommentsByArticleId(articleId);
        return Result.success(comments);
    }

    @Override
    public Result saveComments(Comments comments) {
        Comments save = commentsRepository.save(comments);
        return Result.success(save);
    }

    @Override
    public Result saveReply(Reply reply, String commentId) {
        // 查询评论
        Comments comments = commentsRepository.findCommentsById(commentId);
        List<Reply> replyList = comments.getReplyList();
        if(replyList==null){
            replyList = new ArrayList<>();
        }
        replyList.add(reply);
        // 更新comments
        Criteria where = Criteria.where("id").is(commentId);
        Query query = Query.query(where);
        Update update = Update.update("replyList", replyList);
        UpdateResult result = mongoTemplate.updateFirst(query, update, Comments.class);
        // 返回刚刚插入的回复信息
        if(result.getModifiedCount() >0){
            return Result.success(reply);
        }
        return Result.fail("添加回复失败");
    }
}
